{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "f2a6e764",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoModelForMaskedLM, AutoTokenizer, AutoConfig"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a7db2a4f",
   "metadata": {},
   "outputs": [],
   "source": [
    "config = AutoConfig.from_pretrained('microsoft/deberta-v3-base')\n",
    "tokenizer = AutoTokenizer.from_pretrained('malaysia-ai/bpe-tokenizer')\n",
    "special_tokens_dict = {\"mask_token\": \"[MASK]\"}\n",
    "num_added_toks = tokenizer.add_special_tokens(special_tokens_dict)\n",
    "config.vocab_size = len(tokenizer)\n",
    "config.max_position_embeddings = 4096"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c67c07df",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "DebertaV2Config {\n",
       "  \"_name_or_path\": \"microsoft/deberta-v3-base\",\n",
       "  \"attention_probs_dropout_prob\": 0.1,\n",
       "  \"hidden_act\": \"gelu\",\n",
       "  \"hidden_dropout_prob\": 0.1,\n",
       "  \"hidden_size\": 768,\n",
       "  \"initializer_range\": 0.02,\n",
       "  \"intermediate_size\": 3072,\n",
       "  \"layer_norm_eps\": 1e-07,\n",
       "  \"max_position_embeddings\": 4096,\n",
       "  \"max_relative_positions\": -1,\n",
       "  \"model_type\": \"deberta-v2\",\n",
       "  \"norm_rel_ebd\": \"layer_norm\",\n",
       "  \"num_attention_heads\": 12,\n",
       "  \"num_hidden_layers\": 12,\n",
       "  \"pad_token_id\": 0,\n",
       "  \"pooler_dropout\": 0,\n",
       "  \"pooler_hidden_act\": \"gelu\",\n",
       "  \"pooler_hidden_size\": 768,\n",
       "  \"pos_att_type\": [\n",
       "    \"p2c\",\n",
       "    \"c2p\"\n",
       "  ],\n",
       "  \"position_biased_input\": false,\n",
       "  \"position_buckets\": 256,\n",
       "  \"relative_attention\": true,\n",
       "  \"share_att_key\": true,\n",
       "  \"transformers_version\": \"4.35.0\",\n",
       "  \"type_vocab_size\": 0,\n",
       "  \"vocab_size\": 32001\n",
       "}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "config"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e89d330e",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = AutoModelForMaskedLM.from_config(config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "28480ee6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('debertav2-base/tokenizer_config.json',\n",
       " 'debertav2-base/special_tokens_map.json',\n",
       " 'debertav2-base/tokenizer.json')"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.save_pretrained('debertav2-base')\n",
    "tokenizer.save_pretrained('debertav2-base')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "69e4d5b8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "config.json\t   special_tokens_map.json  tokenizer_config.json\r\n",
      "model.safetensors  tokenizer.json\r\n"
     ]
    }
   ],
   "source": [
    "!ls debertav2-base"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "7ded1819",
   "metadata": {},
   "outputs": [],
   "source": [
    "from streaming.base.format.mds.encodings import Encoding, _encodings\n",
    "from streaming import StreamingDataset\n",
    "import torch\n",
    "import numpy as np\n",
    "\n",
    "class UInt16(Encoding):\n",
    "    def encode(self, obj) -> bytes:\n",
    "        return obj.tobytes()\n",
    "\n",
    "    def decode(self, data: bytes):\n",
    "        return np.frombuffer(data, np.uint16)\n",
    "\n",
    "_encodings['uint16'] = UInt16\n",
    "\n",
    "class DatasetFixed(torch.utils.data.Dataset):\n",
    "    def __init__(self, local):\n",
    "        self.dataset = StreamingDataset(local=local)\n",
    "\n",
    "    def __getitem__(self, idx):\n",
    "        data = self.dataset[idx]\n",
    "        data.pop('token_type_ids', None)\n",
    "        for k in data.keys():\n",
    "            data[k] = data[k].astype(np.int64)\n",
    "        return data\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.dataset)\n",
    "\n",
    "train_dataset = DatasetFixed(local='tokenized-512')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "461ad7c4",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import DataCollatorForLanguageModeling\n",
    "\n",
    "data_collator = DataCollatorForLanguageModeling(\n",
    "    tokenizer=tokenizer,\n",
    "    mlm_probability=0.15,\n",
    "    pad_to_multiple_of=None,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "d04f1ad4",
   "metadata": {},
   "outputs": [],
   "source": [
    "batch = [train_dataset[i] for i in range(3)]\n",
    "b = data_collator(batch)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "38540f61",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "MaskedLMOutput(loss=tensor(10.5440, grad_fn=<NllLossBackward0>), logits=tensor([[[ 0.0000,  0.6299,  0.3935,  ...,  0.1540, -0.2767, -0.8502],\n",
       "         [ 0.0000,  0.6043, -0.7251,  ..., -0.1069,  0.7736, -0.1743],\n",
       "         [ 0.0000,  0.5119,  0.2992,  ...,  0.2536, -0.2253, -0.4136],\n",
       "         ...,\n",
       "         [ 0.0000,  0.8840,  0.2400,  ..., -0.2831,  0.3892,  0.3696],\n",
       "         [ 0.0000,  0.6039, -0.1760,  ..., -0.2009,  0.0234, -0.1737],\n",
       "         [ 0.0000,  0.3058, -0.1681,  ...,  0.8590,  0.1530, -0.2431]],\n",
       "\n",
       "        [[ 0.0000,  0.0809, -0.0523,  ...,  0.0676, -0.5746,  0.1287],\n",
       "         [ 0.0000,  0.0800, -0.2212,  ...,  0.4210,  0.4900, -0.0251],\n",
       "         [ 0.0000,  0.3146,  0.1671,  ..., -0.4739,  0.5507, -0.5570],\n",
       "         ...,\n",
       "         [ 0.0000, -0.1627, -0.0639,  ...,  0.6361,  0.6218, -0.2991],\n",
       "         [ 0.0000,  0.2889,  0.1489,  ...,  0.5500,  0.8279,  0.2799],\n",
       "         [ 0.0000,  0.7858, -0.8017,  ...,  0.9580,  0.9399,  0.0629]],\n",
       "\n",
       "        [[ 0.0000,  0.6794,  0.7442,  ...,  0.9696, -0.7895,  0.2751],\n",
       "         [ 0.0000,  0.0182,  0.7212,  ..., -0.0293,  0.8613, -0.0358],\n",
       "         [ 0.0000,  0.0685, -0.2552,  ...,  0.1793,  0.5789,  0.0229],\n",
       "         ...,\n",
       "         [ 0.0000,  0.7650, -0.8396,  ...,  0.7415,  0.4195,  0.5323],\n",
       "         [ 0.0000,  0.5404, -0.2474,  ..., -1.2498, -1.2980, -1.0519],\n",
       "         [ 0.0000,  1.2308,  0.7562,  ..., -0.7517,  0.3781,  0.4318]]],\n",
       "       grad_fn=<ViewBackward0>), hidden_states=None, attentions=None)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model(**b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8a7061de",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
